require('newrelic');
require('dotenv').config({ silent: false });
require('loopback-component-passport');
global.Promise = require('bluebird');
const loopback = require('loopback');
const boot = require('loopback-boot');
const debug = require('debug')('node_arch:server');
const { createServer } = require('./modules/create-server');

const app = loopback();
module.exports = app;

app.start = async function startApp() {
  const server = await createServer(app);
  return server.listen(app.get('port'), () => {
    const baseUrl = `${(app.get('HTTP') ? 'http' : 'https')}://${app.get('host')}:${app.get('port')}`;
    app.emit('started', baseUrl);
    debug('LoopBack server listening @ %s%s', baseUrl, '/');
    if (app.get('loopback-component-explorer')) {
      const explorerPath = app.get('loopback-component-explorer').mountPath;
      debug('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, (err) => {
  if (err) throw err;

  // start the server if `$ node server.js`
  if (require.main === module) {
    app.start();
  }
});
